Python
Ways to Make Python Bearable
-
Enable Pylance.
-
Always use Hints.
-
Rethink your decisions.
PyLance: VSCode
// Python
"[python]": {
"editor.formatOnType": true
},
"python.defaultInterpreterPath": "C:\\Users\\caior\\AppData\\Local\\Programs\\Python\\Python313\\python.exe",
"python.terminal.shellIntegration.enabled": true,
"python.analysis.autoImportCompletions": true,
"python.analysis.displayEnglishDiagnostics": true,
"python.analysis.generateWithTypeAnnotation": true,
"python.analysis.inlayHints.callArgumentNames": "all",
// Python: Security
"python.analysis.typeCheckingMode": "strict",
"python.analysis.languageServerMode": "full",
"python.analysis.logLevel": "Error",
"python.analysis.typeEvaluation.strictListInference": true,
"python.analysis.typeEvaluation.strictDictionaryInference": true,
"python.analysis.typeEvaluation.strictSetInference": true,
"python.analysis.typeEvaluation.enableReachabilityAnalysis": true,
"python.analysis.typeEvaluation.disableBytesTypePromotions": true,
"python.analysis.typeEvaluation.deprecateTypingAliases": true,
"python.analysis.autoFormatStrings": true,
"python.analysis.inlayHints.pytestParameters": true,
"python.analysis.inlayHints.functionReturnTypes": true,
"python.analysis.inlayHints.variableTypes": true,
"python.missingPackage.severity": "Error",
About
Basics
Basics
-
Light demonstration of classes; __init__ in classes; self keyword .
-
"Self is: This instance of the class".
-
Typing
-
Only used for documentation, it doesn't change anything in the code.
-
Can be used with mypy to perform type checking during code compilation, but it's annoying because it still provides no real safety/checks while writing code.
-
Generic Types (T) for functions in Python 3.12 .
-
In Python 3.12 you can use 'any' type for generic functions.
-
-
Cython .
-
"Cython is a superset of Python syntax - almost any valid Python code is also valid Cython code. The Cython compiler translates the quasi-Python source code to not-for-human-eyes C, which can then be compiled into a shared object and loaded as a Python module."
-
"You can basically take your Python code and add as many or as few static type declarations as you like. Wherever types are undeclared, Cython will add in the necessary boilerplate to correctly infer them, at the cost of worse runtime performance. This essentially allows you to choose a point in the continuum between totally dynamically typed Python code and totally statically typed C code, depending on how much runtime performance you need and how much time you are prepared to spend optimizing. It also allows you to call C functions directly, making it a very convenient way to write Python bindings for external libraries."
-
-
Tips to Improve Function Syntax* .
-
Tip 4 shows the use of an 'asterisk' in functions, indicating that the type should be passed during the function call.
-
Debug
-
You can use
passor...to 'pass' a function. -
Comments are done with
#or""" multi-line """.
Random Commands
Ternary
-
[i * 10 for i in eixo_y0].
Pause terminal
-
os.system("pause") -
or
-
input()
Type Check
if type(lista[0]) == str:
print('lista[0] is a string')
Formatting, etc.
-
Convert all floats to .2f and change to string.
-
a = str('%.2f' % a)
-
Network
WebSockets
APIs
-
Create an API using Flask and Ngrok .
-
Flask seems to be the most important. Not sure
-
Matplotlib (Graphs)
-
Colors .
-
Function .plot and how to change plot style (at the bottom of the page) .
-
In the case of 'subplot', functions switch to using 'ax.xlabel' instead of 'plt.xlabel'. This happens when plotting multiple separate graphs.
PyInstaller (Create .exe)
Version I use
-
pyinstaller --onefile --noconsole music_player.py
Create an .exe
-
You can create an executable file for your Python application using various tools available. One popular tool for creating standalone executables is
PyInstaller. PyInstaller analyzes your Python program to discover every other module and library your program needs in order to execute. -
Here are the steps to create an executable using PyInstaller:
-
Install PyInstaller : If you haven't installed PyInstaller yet, you can install it via pip:
-
pip install pyinstaller
-
-
Create the Executable : Navigate to the directory containing your Python script (
music_player.pyin this case) in the command line and run the following command:-
pyinstaller --onefile music_player.py -
Replace
music_player.pywith the name of your Python script.
-
-
Find the Executable : Once PyInstaller finishes its job, you'll find a
distdirectory created in your project folder. Inside thedistdirectory, there will be an executable file namedmusic_player.exe(or whatever name your Python script had).
-
-
Now, you can simply double-click on
music_player.exeto run your application without needing to compile the Python code each time. -
Keep in mind that PyInstaller packages your entire application, including all necessary dependencies, into a single executable file. This means that the executable may be larger in size compared to the original Python script. Additionally, the process might be different if you're using third-party libraries that require special handling.
Add dependencies
-
When you create a standalone executable using PyInstaller, it packages only the files that are explicitly imported or accessed by your Python script. If your script relies on external files like
favoritos.json, PyInstaller won't automatically include them in the packaged executable. -
To resolve this issue, you need to make sure that
favoritos.jsonis included in the packaged executable. Here's how you can do it:-
Ensure
favoritos.jsonis in the same directory as the executable : The simplest solution is to placefavoritos.jsonin the same directory as the generated executable (music_player.exe). This way, your script can access it without any modification. -
Include
favoritos.jsonin the PyInstaller bundle : If you wantfavoritos.jsonto be bundled with the executable, you can use the--add-dataoption of PyInstaller to include it. For example:-
pyinstaller --onefile --add-data "favoritos.json;." music_player.py -
This command tells PyInstaller to include
favoritos.jsonand place it in the same directory as the executable. You need to adjust the command based on the actual location offavoritos.jsonand your Python script.
-
-
-
Choose the approach that best fits your needs, and then recompile the executable. Once
favoritos.jsonis properly included, your executable should be able to access it without any errors. -
Here,
"favoritos.json;."specifies that you want to includefavoritos.jsonand place it in the root directory of the bundled executable (.denotes the current directory).-
"favoritos.json"is the path to the file you want to include. -
;separates the source path from the destination path. -
.specifies the destination directory where you want to place the file relative to the root of the bundled executable.
-
Embed dependencies
-
Yes, you can embed the contents of the JSON file directly into your Python script as a string. This way, you won't need the external JSON file, and your program will remain a single-file executable.
-
Here's how you can do it:
-
Open your
favoritos.jsonfile and copy its contents. -
Paste the contents as a string in your Python script, assigning it to a variable.
-
Modify your code to use this embedded JSON string instead of reading from the external file.
-
Remove the Console
-
To prevent the terminal window from appearing when running the executable, you need to use the
--noconsoleoption with PyInstaller when creating the executable. This option tells PyInstaller not to create a console window along with the GUI window. -
Here's how you can modify the PyInstaller command to include the
--noconsoleoption:-
pyinstaller --onefile --noconsole --add-data "favoritos.json;." music_player.py(No need to use --add-data if embedded)
-
-
With this modification, the executable will run without displaying a separate terminal window. Make sure to recompile your executable with this updated command.